//
//  XSJComposeTextView+Extension.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/23.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit


extension XSJComposeTextView {

    
    var emticonText : String {
    
        var result = ""
        
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
            if let attachment = infoDic["NSAttachment"] as? XSJTextAttachment {
                
                let chs = attachment.emoticon!.chs!
                result += chs
            } else {
                
                
                let text = self.attributedText.attributedSubstringFromRange(range).string
                result += text
                
            }

        }
        
      return result
    }
    
    
    func insertEmoticon(emoticon: XSJEmoticon, font: UIFont) {
    
        if emoticon.type == "0" {
            
            
            var originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
            let image = UIImage(named: emoticon.path!)
            let attachtment = XSJTextAttachment()
            
            attachtment.emoticon = emoticon
            
            attachtment.image = image
            
            let fontHeight = self.font?.lineHeight
            
            attachtment.bounds = CGRect(x: 0, y: -4, width: fontHeight!, height: fontHeight!)
            
            let attr = NSAttributedString(attachment: attachtment)
            
            //  获取textview的选中范围
            var range = self.selectedRange
            //  替换选中的字符串
            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)
            
            //  追加富文本
            //originalAttr.appendAttributedString(attr)
            
            //  设置富文本的字体大小
            originalAttr.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, originalAttr.length))
            
            //  设置富文本
            self.attributedText = originalAttr
            //  每次点击表情开始位置加一
            range.location += 1
            //  设置选中范围长度为0
            range.length = 0
            
            //  设置选中范围
            self.selectedRange = range
            
           
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            self.delegate?.textViewDidChange?(self)
            
            
            
            
            
            

            
        }else{
            
            self.insertText((emoticon.code! as NSString).emoji())
            
        }

        
    }
    
    
}
